package com.codepilot.server.controller;

import com.codepilot.server.model.dto.UserDTO;
import com.codepilot.server.model.entity.Record;
import com.codepilot.server.model.vo.CommonResult;
import com.codepilot.server.service.RecordService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = {"做题记录"})
@RestController
@RequestMapping ("/api/record")
public class RecordController {
    @Autowired
    private RecordService recordService;

    @GetMapping
    public CommonResult<List<Record>> getRecordList(@RequestHeader("Authorization") String token) {
        Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authorization.getPrincipal();
        return CommonResult.success(recordService.getRecordList(loginUser.getUser().getId()));
    }

    // 用户点击题目链接时, 新建做题记录
    @PostMapping("/{problemUid}")
    public CommonResult<Integer> createRecord(@RequestHeader("Authorization") String token,
                                              @PathVariable("problemUid") String problemUid) {
        Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authorization.getPrincipal();
        return CommonResult.success(recordService.createRecord(loginUser.getUser().getId(), Integer.parseInt(problemUid)));
    }

    @PostMapping
    public CommonResult<Integer> finishRecord(@RequestHeader("Authorization") String token, @RequestBody Record record) {
        Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
        UserDTO loginUser = (UserDTO) authorization.getPrincipal();
        record.setUserId(loginUser.getUser().getId());
        return CommonResult.success(recordService.finishRecord(record));
    }
}
